package net.xfok.words.cet4;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.view.View.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.LinearLayout;

public class Main extends Activity implements OnClickListener{
	private static String TAG="Main";
	
	private static int BUFFER_SIZE=1024;
	private static int GAP=5000;
	private static final String mimeType = "text/html";
	private static final String encoding = "utf-8";
	private final int MENU_AUTO= Menu.FIRST;
	private final int MENU_NEXT = Menu.FIRST+1;
	private final int MENU_PRE = Menu.FIRST+2;
    
	private int id=0;
	private boolean auto=false;
	private String query="";
	private WebView wv;
	private AutoCompleteTextView atv;
	private Button btSearch,btStop,btAuto,btNext,btPre;
	private LinearLayout searchPanel;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        searchPanel=(LinearLayout)findViewById(R.id.search_panel);
        wv=(WebView)findViewById(R.id.web_view);
        atv=(AutoCompleteTextView)findViewById(R.id.key);        
        btSearch=(Button)findViewById(R.id.bt_search);
        btStop=(Button)findViewById(R.id.bt_stop);
        btAuto=(Button)findViewById(R.id.bt_auto);
        btNext=(Button)findViewById(R.id.bt_next);
        btPre=(Button)findViewById(R.id.bt_pre);
        btSearch.setOnClickListener(this);   
        btStop.setOnClickListener(this); 
        btAuto.setOnClickListener(this);   
        btNext.setOnClickListener(this); 
        btPre.setOnClickListener(this);
        btStop.setVisibility(View.GONE);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, Constant.words);
        atv.setAdapter(adapter);
        search();
    }
    
    @Override
    public void onConfigurationChanged(Configuration config) {
        try {
            super.onConfigurationChanged(config);
            if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                
            }
        } catch (Exception ex) {
        }
    }
   
    private void search(){
    	Log.i(TAG, "id="+id);
    	if(id<0)id=0;
    	id=id%Constant.words.length;
    	String word=Constant.words[id];
    	setTitle(word+" - "+getResources().getString(R.string.app_name));
        try{
        	String mean=inputStream2String(getAssets().open(word));
        	String data=getHtml(word, mean);
        	wv.loadData(data, mimeType, encoding);       	    	
        }catch(Exception e){
        	e.printStackTrace();
        }
        if(auto){   
        	Message message = new Message();
       	 	message.what = 0;      
       	 	handler.sendMessageDelayed(message, GAP) ;
        }
    }
    
    private void search(String word){
    	 setTitle(word+" - "+getResources().getString(R.string.app_name));
         try{
         	String mean=inputStream2String(getAssets().open(word));
         	String data=getHtml(word, mean);
         	wv.loadData(data, mimeType, encoding);
         	for(int i=0;i<Constant.words.length;i++){
         		if(word.equals(Constant.words[i])){
         			id=i;
         			break;
         		}
     		}         	
         }catch(Exception e){
         	e.printStackTrace();
         }     
    }
    
    public void onClick(View v) {
		switch(v.getId()){
			case R.id.bt_search:
				if(atv.getText().toString()!=null&&!atv.getText().toString().trim().equals(query)){
					query=atv.getText().toString();
					search(query);
				}								
				break;	
			case R.id.bt_auto:
				auto();
				break;
			case R.id.bt_stop:				
				stop();
				break;
			case R.id.bt_next:
				id++;
		        search();
				break;
			case R.id.bt_pre:
				id--;
			    search();
				break;
		}  	
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {      
    	menu.add(0, MENU_PRE, 0, getResources().getString(R.string.menu_pre)).setIcon(R.drawable.ic_menu_pre);
        menu.add(0, MENU_AUTO, 0, getResources().getString(R.string.menu_auto)).setIcon(android.R.drawable.ic_menu_more);       
        menu.add(0, MENU_NEXT, 0, getResources().getString(R.string.menu_next)).setIcon(R.drawable.ic_menu_next);       
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
	        case MENU_AUTO:
	            Log.i(TAG, "=======AUTO=======");
	            auto();
	            break;
	    	case MENU_NEXT:
		        Log.i(TAG, "=======NEXT=======");
		        id++;
		        search();
		        break;
	    	case MENU_PRE:
		        Log.i(TAG, "=======PRE=======");	
		        id--;
		        search();
		        break;	    	
        }
        return true;
    }
    
    private void auto(){
    	auto=true;
    	query="";
    	atv.setText("");
    	searchPanel.setVisibility(View.GONE);
		btStop.setVisibility(View.VISIBLE);
		btNext.setVisibility(View.GONE);
		btPre.setVisibility(View.GONE);
    	id++;
    	search();
    }
    
    private void stop(){ 
    	auto=false;
    	searchPanel.setVisibility(View.VISIBLE);	
    	btStop.setVisibility(View.GONE);
		btNext.setVisibility(View.VISIBLE);
		btPre.setVisibility(View.VISIBLE);
    	handler.removeMessages(0);
    }
    
    Handler handler = new Handler(){  		  
        public void handleMessage(Message msg) {      
        	id++;
        	search();
            super.handleMessage(msg);  
        }        
    };  
    
    private String inputStream2String(InputStream is){
	    BufferedReader in = new BufferedReader(new InputStreamReader(is));
	    StringBuffer buffer = new StringBuffer(BUFFER_SIZE);
	    try{
	 	    String line = "";	   
		    while ((line = in.readLine()) != null){
		        buffer.append(line);
		    }
	    }catch(Exception e){
		    e.printStackTrace();
	    }
	    return buffer.toString();
 	}
    
    private String getHtml(String word,String mean){
		StringBuilder html = new StringBuilder();
        html.append("<html><head><title>")
        .append(word)
        .append("</title>\n")
        .append(CSS)
        .append("</head><body>")
        .append(mean)
        .append(STAT)
        .append("</body></html>");
        return html.toString();
	}
    
	private static final String CSS;
	private static final String STAT;
	static {
        CSS = new StringBuilder()
                .append("<style type=\"text/css\">\n")
                .append("<!--\n")
                .append("body,div,ol{font-size: 14px; margin: 0pt; color:#000;list-style:none;border:none;}\n")
                .append(".p {font-family: Lucida Sans Unicode; color: #666699;}\n")
                .append("a {color: #414141;}\n")
                .append(".b {font-weight:bold;}\n")
                .append(".k {color: green;font-weight:bold;}\n")
                .append(".h {color:#cc0066}\n")
                .append(".t {font-weight:bold;color:#666666;font-style:italic;}\n")
                .append("-->\n")
                .append("</style>\n")
                .toString();
        STAT = new StringBuilder()
				.append("<div style=\"display:none\">")
				.append("<iframe height=\"0\" width=\"0\" src=\"http://www.xfok.net/xdict/cet4.html\"></iframe>")
				.append("<script language=\"javascript\" type=\"text/javascript\" src=\"http://js.users.51.la/2686715.js\"></script><noscript><a href=\"http://www.51.la/?2686715\" target=\"_blank\"><img alt=\"&#x6211;&#x8981;&#x5566;&#x514D;&#x8D39;&#x7EDF;&#x8BA1;\" src=\"http://img.users.51.la/2686715.asp\" style=\"border:none\" /></a></noscript> <script language=\"javascript\" src=\"http://count32.51yes.com/click.aspx?id=320483963&logo=1\" charset=\"gb2312\"></script></div></body></html><div style=\"display:none\"><script language=\"javascript\" type=\"text/javascript\" src=\"http://js.users.51.la/2686715.js\"></script><noscript><a href=\"http://www.51.la/?2686715\" target=\"_blank\"><img alt=\"&#x6211;&#x8981;&#x5566;&#x514D;&#x8D39;&#x7EDF;&#x8BA1;\" src=\"http://img.users.51.la/2686715.asp\" style=\"border:none\" /></a></noscript> <script language=\"javascript\" src=\"http://count32.51yes.com/click.aspx?id=320483963&logo=1\" charset=\"gb2312\"></script>")
				.append("</div>").toString();
    }
	
}